package net.hcpme.activity.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class HttpDownloader {

    interface OnDownloadListener {
        public void onDownloadUpdate(HttpDownloader manager, int percent);

        public void onDownloadError(HttpDownloader manager, Exception e);

        public void onDownloadConnect(HttpDownloader manager);

        public void onDownloadComplete(HttpDownloader manager, Object result);
    }

    private OnDownloadListener onDownloadListener;
    private URL url = null;

    /**
     * ���URL�����ļ�,ǰ��������ļ����е��������ı�,����ķ���ֵ�����ı����е����� 1.����һ��URL����
     * 2.ͨ��URL����,����һ��HttpURLConnection���� 3.�õ�InputStream 4.��InputStream���ж�ȡ���
     * 
     * @param urlStr
     * @return
     */
    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * 
     * @param urlStr
     * @param path
     * @param fileName
     * @return -1:�ļ����س��� 0:�ļ����سɹ� 1:�ļ��Ѿ�����
     */
    public void downFile(String urlStr, String path, String fileName) {
        String filename = fileName.substring(fileName.lastIndexOf("/") + 1);
        path += fileName.substring(0, fileName.lastIndexOf("/") + 1);
        InputStream inputStream = null;
        OutputStream output = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File dir = new File(path);
                if (!dir.exists()) {
                    // �������ڣ�����Ŀ¼��������Ӧ��������ʱ�򴴽�
                    dir.mkdirs();
                }
            } else {
                return;
            }

            File file = new File(path + filename);
            file.createNewFile();

            inputStream = getInputStreamFromURL(urlStr);

            output = new FileOutputStream(file);

            byte[] buffer = new byte[1024 * 4];
            while (inputStream.read(buffer) != -1) {
                output.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
            onDownloadListener.onDownloadError(this, e);
        } finally {
            try {
                output.flush();
                output.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        onDownloadListener.onDownloadComplete(this, 1);
    }

    /**
     * ���URL�õ�������
     * 
     * @param urlStr
     * @return
     */
    public InputStream getInputStreamFromURL(String urlStr) {
        HttpURLConnection urlConn = null;
        InputStream inputStream = null;
        try {
            url = new URL(urlStr);
            urlConn = (HttpURLConnection) url.openConnection();
            inputStream = urlConn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return inputStream;
    }

    /**
     * ��ȡ����ͼƬ��Դ
     * 
     * @param url
     * @return
     */

    public static Bitmap getHttpBitmap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            // �������
            HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
            // ���ó�ʱʱ��Ϊ6000���룬conn.setConnectionTiem(0);��ʾû��ʱ������
            conn.setConnectTimeout(6000);
            // �������û�������
            conn.setDoInput(true);
            // ��ʹ�û���
            conn.setUseCaches(false);
            // �����п��ޣ�û��Ӱ��
            // conn.connect();
            // �õ������
            InputStream is = conn.getInputStream();
            // �����õ�ͼƬ
            bitmap = BitmapFactory.decodeStream(is);
            // �ر������
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
        this.onDownloadListener = onDownloadListener;
    }
}